package com.draven.mall.dispatch;

import com.draven.mall.entity.Order;
import com.draven.mall.entity.Rider;
import com.draven.mall.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 最少订单骑手优先算法实现
 * 选择当前配送中订单数量最少的骑手进行分配
 */
@Component
public class LeastOrdersDispatchAlgorithm implements DispatchAlgorithm {

    private static final Logger log = LoggerFactory.getLogger(LeastOrdersDispatchAlgorithm.class);

    @Autowired
    private OrderService orderService;

    @Override
    public Rider assignRider(Order order, List<Rider> availableRiders) {
        if (availableRiders == null || availableRiders.isEmpty() || order == null) {
            return null;
        }
        
        try {
            // 获取每个骑手当前的配送中订单数量
            Map<Long, Integer> riderOrderCounts = new HashMap<>();
            
            for (Rider rider : availableRiders) {
                // 获取骑手配送中的订单
                Map<String, Object> result = orderService.getInProgressOrders(rider.getId(), 1, 100);
                int count = result != null && result.get("total") != null ? 
                        Integer.parseInt(result.get("total").toString()) : 0;
                
                riderOrderCounts.put(rider.getId(), count);
            }
            
            // 找到配送中订单数量最少的骑手
            Optional<Rider> leastOrdersRider = availableRiders.stream()
                .min(Comparator.comparingInt(rider -> 
                    riderOrderCounts.getOrDefault(rider.getId(), Integer.MAX_VALUE)
                ));
            
            return leastOrdersRider.orElse(null);
        } catch (Exception e) {
            log.error("计算骑手订单数时发生异常", e);
            return availableRiders.isEmpty() ? null : availableRiders.get(0);
        }
    }

    @Override
    public int getType() {
        return 4; // 算法类型：4-最少订单骑手优先
    }

    @Override
    public String getName() {
        return "最少订单骑手优先";
    }
} 